//
//  MemberUpdateLoginPwdViewController.m
//  myhuibao
//
//  Created by lijun on 13-3-11.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "MemberFavoriteLisViewController.h"
#import "RestaurantDetailViewController.h"
#import <UIKit/UIKit.h>
#import "Config.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"
#import "SearchCell.h"
#import "LoadMoreCell.h"
#import "OMGToast.h"
#import "RequestLoadingView.h"

@interface MemberFavoriteLisViewController ()

@end

@implementation MemberFavoriteLisViewController
@synthesize mainTable;
@synthesize req;
@synthesize reqMore;
@synthesize reqClear;
@synthesize reqDelete;
static int stype=1;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
//-(void) viewWillAppear:(BOOL)YSE{
//    stype=1;
//    [super viewWillAppear:YES];
//    wqTable=mainTable;
//    pageIndex=1;
//    NSURL *url = [NSURL URLWithString:url_getfavoriteList];
//    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
//    [request setPostValue:[NSString stringWithFormat:@"%d",pageIndex++] forKey:@"pageIndex"];
//    
//    int memberId = [[Config Instance] getMemberId];
//    NSString *password=[[Config Instance] getPassword];
//    NSString *sid=[NSString stringWithFormat:@"%d",memberId];
//    [request setPostValue:password forKey:@"password"];
//    [request setPostValue:sid forKey:@"memberID"];
////    [request setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLatitude]] forKey:@"latitude"];
////    [request setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLongitude]] forKey:@"longitude"];
//    [request setShouldAttemptPersistentConnection:NO];
//    [request setDelegate: self];
//    [request startAsynchronous];
//
//}
- (void)startRequest
{
    if(!loadingView){
        
        loadingView = [[RequestLoadingView alloc]
                       initRequestLoadingView:self
                       queueFinishSelector:nil
                       viewFrame:LoadingViewFrame];
        
    }
    
    [loadingView addRequestToQueue:req];

    [loadingView startRequestQueue];

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    wqTable=mainTable;
    pageIndex=1;
    NSURL *url = [NSURL URLWithString:url_getfavoriteList];
    req=[ASIFormDataRequest requestWithURL:url];
    [req setPostValue:[NSString stringWithFormat:@"%d",pageIndex++] forKey:@"pageIndex"];
    
    int memberId = [[Config Instance] getMemberId];
    NSString *password=[[Config Instance] getPassword];
    NSString *sid=[NSString stringWithFormat:@"%d",memberId];
    [req setPostValue:password forKey:@"password"];
    [req setPostValue:sid forKey:@"memberID"];
//    [request setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLatitude]] forKey:@"latitude"];
//    [request setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLongitude]] forKey:@"longitude"];
    [req setShouldAttemptPersistentConnection:NO];
    [req setDidFinishSelector:@selector(finishReq:)];
    isReqFinished = false;
    [req setDelegate: self];

 //   [req startAsynchronous];

    [self startRequest];

	// Do any additional setup after loading the view.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    //[mainTable release];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}



//下面是两个代理函数,当数据请求成功时会调用requestFinished，请求失败时（如网络问题或服务器内部错误）会调用requestFailed
- (void)finishReq:(ASIHTTPRequest *)request
{
    isReqFinished = true;
      NSString *jsonStr = [request responseString];
      //NSLog(@"%@",jsonStr);
      NSDictionary *dic = [jsonStr JSONValue];
    if([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"]){
      tableDataArray = [dic valueForKey:@"data"];
      //NSLog(@"%@", tableDataArray);
      returnCount = [tableDataArray count];
        if (returnCount==0) {
            [OMGToast showWithText:@"您还没有收藏商户。" bottomOffset:100];
        }
      delegate=self;
      [mainTable reloadData];
      [Config setExtraCellLineHidden:mainTable];

    }
//    else {
//        UIAlertView *view=[[UIAlertView alloc]initWithTitle:APP_TITLE message:[dic valueForKey:@"log"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [view show];
//        [view release];
//        return;
//    }
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
    if (error.code==net_failure_code) {
        [OMGToast showWithText:net_failure_msg bottomOffset:100];
    }
    isReqFinished = true;
    isReqMoreFinished = true;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    if (count>=pageSize) {
        return count+1;
    }else
        return count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row] < ([tableDataArray count])) {
        return 90;
    }else{
        return 40;
    }}
- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"SearchCellIdentifier";
    
    
    if([indexPath row] < ([tableDataArray count])) {
        
        SearchCell *cell = (SearchCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
                if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"SearchCell" owner:nil options:nil];
        cell = [array objectAtIndex:0];
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
                }
        
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        
        cell.name = [item valueForKey:@"name"];
        cell.address = [item valueForKey:@"address"] ;
        cell.distance = [item valueForKey:@"distance"] ==[NSNull null]?@"" : [NSString stringWithFormat:@"%f",[[item valueForKey:@"distance"] floatValue] ];
//        cell.cuisine = [item valueForKey:@"cuisine"] ==[NSNull null]?@"未知" : [item valueForKey:@"cuisine"];
        int type=[[item valueForKey:@"merchantTypeID"] intValue];
        if(type==1)
        {
            cell.cuisine=@"餐饮";
        }
        else if (type==2)
        {
            cell.cuisine=@"KTV";
        }
        else if(type==3)
        {
            cell.cuisine=@"咖啡茶馆";
        }
        cell.discount = [item valueForKey:@"discount"] ==[NSNull null]?@"10":[[item valueForKey:@"discount"]stringValue];
        cell.score = [item valueForKey:@"score"] == [NSNull null]? [NSNumber numberWithFloat:0] : [NSNumber numberWithFloat:[[item valueForKey:@"score"] floatValue]];
        
        //        显示图片
        NSString * imageStr = [[tableDataArray objectAtIndex:indexPath.row] valueForKey:@"image"];
        NSString *imageName =@"";
        if (![imageStr isEqual:[NSNull null] ]) {
            NSArray *array = [imageStr componentsSeparatedByString:@"/"];
            imageName = [array lastObject];
        }
        NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:imageName]];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageDataPath]];
        if (image) {
            cell.imageView.image = image;
        }
        else
        {
            cell.imageView.image = [UIImage imageNamed:@"placeholder.png"];
            //placeholder为在未加载完成加载图片时显示的默认图片
        }
        if([item valueForKey:@"isCard"]!=[NSNull null] && [[item valueForKey:@"isCard"] intValue]==1)
        {
            cell.imageCard.hidden=NO;
        }
        else
        {
            cell.imageCard.hidden=YES;
        }
        if([item valueForKey:@"isCoupon"]!=[NSNull null] && [[item valueForKey:@"isCoupon"] intValue]==1)
        {
            cell.imageTicket.hidden=NO;
        }
        else
        {
            cell.imageTicket.hidden=YES;
        }

        return cell;
        
    }else{
        LoadMoreCell *cell = (LoadMoreCell *)[tableView dequeueReusableCellWithIdentifier: @"LoadMoreCellIdentifier"];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"LoadMoreCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        if(returnCount<pageSize){
            cell.lbText.text=@"";
            cell.hidden = true;
        }else{
            //创建loadMoreCell
            cell.lbText.text=str_more;
        }
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.detailTextLabel.text=@"";
        cell.imageView.image =nil;
        return cell;
    }
    
}
-(void)cellImageDidLoad:(NSIndexPath *)indexPath image:(UIImage *)image
{
    dispatch_async(dispatch_get_main_queue(), ^{
        UITableViewCell *cell = [wqTable cellForRowAtIndexPath:indexPath];
        if(image)
        {
            cell.imageView.image = image;
        }
    });
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == [tableDataArray count]) {
        LoadMoreCell *loadMoreCell=(LoadMoreCell *)[tableView cellForRowAtIndexPath:indexPath];
        loadMoreCell.lbText.text=str_loading;
        //        [self performSelectorInBackground:@selector(loadMore) withObject:nil];
        //        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSURL *url = [NSURL URLWithString:url_getfavoriteList];
        reqMore = [ASIFormDataRequest requestWithURL:url];
        [reqMore setPostValue:[NSString stringWithFormat:@"%d",pageIndex++] forKey:@"pageIndex"];
        
        int memberId = [[Config Instance] getMemberId];
        NSString *password=[[Config Instance] getPassword];
        NSString *sid=[NSString stringWithFormat:@"%d",memberId];
        [reqMore setPostValue:password forKey:@"password"];
        [reqMore setPostValue:sid forKey:@"memberID"];
        reqMore.delegate = self;
        isReqMoreFinished = false;
        [reqMore setShouldAttemptPersistentConnection:NO];
        [reqMore setDidFinishSelector:@selector(appendTableWith:)];
        [reqMore startAsynchronous];
//        NSString *jsonStr = [request responseString];
//        
//        NSDictionary *dic = [jsonStr JSONValue];
//        NSMutableArray *array = [dic valueForKey:@"data"];
//        returnCount = [array count];
//        [self performSelectorOnMainThread:@selector(appendTableWith:) withObject:array waitUntilDone:NO];
//        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        //        [dic release];
        //        [array release];
        return;
    }else{
        RestaurantDetailViewController  *view = [[RestaurantDetailViewController alloc] initWithNibName:@"RestaurantDetailViewController" bundle:nil];
        //传递商户id参数
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        view.merchantType=[[item objectForKey:@"merchantTypeID"] intValue];
        view.merchantId =[[item objectForKey:@"ID"] intValue];
        view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
        //        [view release];
        
    }
    //其他cell的事件
    
}
//-(void) appendTableWith:(NSMutableArray *)data
//{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
//    for (int i=0;i<[data count];i++) {
//        [tableDataArray addObject:[data objectAtIndex:i]];
//    }
//    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
//    for (int ind = 0; ind < [data count]; ind++) {
//        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
//        [insertIndexPaths addObject:newPath];
//    }
//    //重新调用UITableView的方法, 来生成行.
//    [self.mainTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
//}
-(void) appendTableWith:(ASIHTTPRequest *)request
{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
    isReqMoreFinished = true;
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSMutableArray *data = [dic valueForKey:@"data"];
    returnCount = [data count];
    //    [self performSelectorOnMainThread:@selector(appendTableWith:) withObject:array waitUntilDone:NO];
    for (int i=0;i<[data count];i++) {
        [tableDataArray addObject:[data objectAtIndex:i]];
    }
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    if ([data count]==0) {
        [self.mainTable reloadData];
    }
    //重新调用UITableView的方法, 来生成行.
    [self.mainTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
//    isSearchMoreFinished = true;
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
    {
        stype=2;
         NSDictionary *dic=[tableDataArray objectAtIndex:indexPath.row];
        [tableDataArray removeObjectAtIndex:indexPath.row];
        NSString *favoriteID=[dic valueForKey:@"favoriteID"];
        int memberID=[[Config Instance] getMemberId];
        NSString *password=[[Config Instance]getPassword];
        NSString *sid=[NSString stringWithFormat:@"%d",memberID];
        NSURL *url=[NSURL URLWithString:url_delfavorite];
        reqDelete=[ASIFormDataRequest requestWithURL:url];
        [reqDelete setPostValue:sid forKey:@"memberID"];
        [reqDelete setPostValue:password forKey:@"password"];
        [reqDelete setPostValue:favoriteID
                       forKey:@"favoriteID"];
        [reqDelete setDidFinishSelector:@selector(finishDelete:)];
        isReqDeleteFinished = false;
        [reqDelete setDelegate:self];
        [reqDelete startAsynchronous];
//        [mainTable reloadData];
}
- (void)finishDelete:(ASIHTTPRequest *)request
{
    isReqDeleteFinished = true;
    NSString *jsonStr = [request responseString];
    //NSLog(@"%@",jsonStr);
    NSDictionary *dic = [jsonStr JSONValue];
    if([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"]){
      UIAlertView *view=[[UIAlertView alloc]initWithTitle:APP_TITLE message:@"删除成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [view show];
        [self viewDidLoad];
    }else{
       // NSLog(@"%@",dic);
    }
}
//修改删除按钮的文字
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删 除";
}

- (IBAction)delAll:(id)sender {
    if(tableDataArray.count==0)
    {
        return;
    }
    UIAlertView*alert = [[UIAlertView alloc]initWithTitle:APP_TITLE
                                                  message:@"是否确认删除"
                                                 delegate:self
                                        cancelButtonTitle:@"取消"
                                        otherButtonTitles:@"确认",nil];
//    ((UILabel*)[[alert subviews] objectAtIndex:1]).textAlignment = UITextAlignmentLeft;
    [alert show];
 }
//定义的委托，buttonindex就是按下的按钮的index值
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex==1){
        pageIndex=1;
        NSURL *url = [NSURL URLWithString:url_clearfavorite];
        reqClear=[ASIFormDataRequest requestWithURL:url];
        [reqClear setDidFinishSelector:@selector(finishDelAll:)];
        int memberId = [[Config Instance] getMemberId];
        NSString *password=[[Config Instance] getPassword];
        NSString *sid=[NSString stringWithFormat:@"%d",memberId];
        [reqClear setPostValue:password forKey:@"password"];
        [reqClear setPostValue:sid forKey:@"memberID"];
        isReqClearFinished = false;
        [reqClear setDelegate: self];
        [reqClear startAsynchronous];
    }

}
-(void) finishDelAll:(ASIHTTPRequest *)request{
    isReqClearFinished = true;
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSString *msg=@"";
    if([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"])
    {
        msg = @"清除成功";
        [tableDataArray removeAllObjects];
        [mainTable reloadData];
    }else{
        //NSLog(@"%@",dic);
        msg = [dic valueForKey:@"log"];
    }
    UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                  message:msg
                                                 delegate:nil
                                        cancelButtonTitle:@"确定"
                                        otherButtonTitles:nil];
    [alert show];

}
- (IBAction)goBack:(id)sender {
    if (!isReqFinished){
        [req clearDelegatesAndCancel];
        [req cancel];
    }
    if (!isReqMoreFinished){
        [reqMore clearDelegatesAndCancel];
        [reqMore cancel];
    }
    if (!isReqClearFinished){
        [reqClear clearDelegatesAndCancel];
        [reqClear cancel];
    }
    if (!isReqDeleteFinished){
        [reqDelete clearDelegatesAndCancel];
        [reqDelete cancel];
    }

    [super.navigationController
     popViewControllerAnimated:YES];
}


@end
